/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.admin.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.ConfigReader;
import etcore.webapp.grouptalk.common.config.Layout;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of settings
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class SettingsAction extends AbstractAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -179303102417387799L;
	/**
	 * 
	 */

	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int NOT_LOGGED = 2;

	// utility constants

	public static final String SET_CONFIG = "setConfig";
	public static final String SET_PROPERTIES = "setProperties";
	public static final String SET_LAYOUT = "setLayout";
	public static final String SET_MENU = "setMenu";
	public static final String SET_LOGO = "setLogo";
	public static final String SET_BANNER = "setBanner";
	public static final String LOGO_EN = "logo_en.jpg";
	public static final String LOGO_LOCAL = "logo_local.jpg";
	public static final String BANNER1_JPG = "banner1.jpg";
	public static final String JPG_SUFFIX = ".jpg";
	public static final String IMG_PATH = "/group/images";
	public static final String GMT = "GMT";
	public static final String GMT8 = "GMT+8";
	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		boolean notLogged = (Boolean) request
				.getAttribute(PageConstants.NOTLOGGED);
		if (notLogged)
			return NOT_LOGGED;

		if (isAdmin) {

			return ACCESS_ALLOWED;
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (NOT_LOGGED == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		return PageConstants.PAGE_PATH_SETTINGS;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		if (ACCESS_ALLOWED == validationResult) {

			setConfig(request);
			setProperties(request);
			setLayout(request);
			setMenu(request);
			try {
				setLogo(request);
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				setBanner(request);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	private void setConfig(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (SET_CONFIG.equals(cmd)) {
			String p1 = request.getParameter(Config.P1);
			String p11 = request.getParameter(Config.P11);
			String p2 = request.getParameter(Config.P2);
			String p22 = request.getParameter(Config.P22);
			String p3 = request.getParameter(Config.P3);
			String p4 = request.getParameter(Config.P4);
			Properties properties = Config.getConfig();
			if (p1 != null
					&& (Messages.TRUE.equals(p1) || Messages.FALSE.equals(p1)))
				properties.setProperty(Config.P1, p1);
			if (p11 != null
					&& (Messages.TRUE.equals(p11) || Messages.FALSE.equals(p11)))
				properties.setProperty(Config.P11, p11);
			if (p2 != null
					&& (Messages.TRUE.equals(p2) || Messages.FALSE.equals(p2)))
				properties.setProperty(Config.P2, p2);
			if (p22 != null
					&& (Messages.TRUE.equals(p22) || Messages.FALSE.equals(p22)))
				properties.setProperty(Config.P22, p22);
			if (p3 != null
					&& (Messages.TRUE.equals(p3) || Messages.FALSE.equals(p3)))
				properties.setProperty(Config.P3, p3);
			if (p4 != null
					&& (Messages.TRUE.equals(p4) || Messages.FALSE.equals(p4)))
				properties.setProperty(Config.P4, p4);

			ConfigReader.storeConfig(properties);
		}

	}
	private void setProperties(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (SET_PROPERTIES.equals(cmd)) {
			String timeZone = request.getParameter(Config.HOURS_DIFFERENCE);
		 
			Properties properties = Config.getConfig();
			 
			if (timeZone != null)
				properties.setProperty(Config.HOURS_DIFFERENCE, timeZone);

			ConfigReader.storeConfig(properties);
		}

	}
	private void setLayout(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (SET_LAYOUT.equals(cmd)) {
			String left = request.getParameter(Layout.LEFT);
			String main_platform1 = request.getParameter(Layout.MAIN_PLATFORM1);
			String main_platform2 = request.getParameter(Layout.MAIN_PLATFORM2);
			String main_platform3 = request.getParameter(Layout.MAIN_PLATFORM3);
			String main_platform4 = request.getParameter(Layout.MAIN_PLATFORM4);
			String main_nav1 = request.getParameter(Layout.MAIN_NAV1);
			String main_nav2 = request.getParameter(Layout.MAIN_NAV2);
			String main_users = request.getParameter(Layout.MAIN_USERS);
			String main_messages = request.getParameter(Layout.MAIN_MESSAGES);
			Properties properties = Layout.getLayout();
			if (left != null)
				properties.setProperty(Layout.LEFT, left);
			if (main_platform1 != null)
				properties.setProperty(Layout.MAIN_PLATFORM1, main_platform1);
			if (main_platform2 != null)
				properties.setProperty(Layout.MAIN_PLATFORM2, main_platform2);
			if (main_platform3 != null)
				properties.setProperty(Layout.MAIN_PLATFORM3, main_platform3);
			if (main_platform4 != null)
				properties.setProperty(Layout.MAIN_PLATFORM4, main_platform4);
			if (main_nav1 != null)
				properties.setProperty(Layout.MAIN_NAV1, main_nav1);
			if (main_nav2 != null)
				properties.setProperty(Layout.MAIN_NAV2, main_nav2);
			if (main_users != null)
				properties.setProperty(Layout.MAIN_USERS, main_users);
			if (main_messages != null)
				properties.setProperty(Layout.MAIN_MESSAGES, main_messages);
			ConfigReader.storeLayout(properties);
		}

	}

	private void setMenu(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (SET_MENU.equals(cmd)) {
			String head_platform0 = request.getParameter(Layout.HEAD_PLATFORM0);
			String head_platform1 = request.getParameter(Layout.HEAD_PLATFORM1);
			String head_platform2 = request.getParameter(Layout.HEAD_PLATFORM2);
			String head_platform3 = request.getParameter(Layout.HEAD_PLATFORM3);
			String head_platform4 = request.getParameter(Layout.HEAD_PLATFORM4);
			String head_nav1 = request.getParameter(Layout.HEAD_NAV1);
			String head_nav2 = request.getParameter(Layout.HEAD_NAV2);

			Properties properties = Layout.getLayout();
			if (head_platform0 != null)
				properties.setProperty(Layout.HEAD_PLATFORM0, head_platform0);
			if (head_platform1 != null)
				properties.setProperty(Layout.HEAD_PLATFORM1, head_platform1);
			if (head_platform2 != null)
				properties.setProperty(Layout.HEAD_PLATFORM2, head_platform2);
			if (head_platform3 != null)
				properties.setProperty(Layout.HEAD_PLATFORM3, head_platform3);
			if (head_platform4 != null)
				properties.setProperty(Layout.HEAD_PLATFORM4, head_platform4);
			if (head_nav1 != null)
				properties.setProperty(Layout.HEAD_NAV1, head_nav1);
			if (head_nav2 != null)
				properties.setProperty(Layout.HEAD_NAV2, head_nav2);

			ConfigReader.storeLayout(properties);
		}

	}

	public void setLogo(HttpServletRequest request) throws IOException {
		String cmd = request.getParameter(PageConstants.CMD);
		if (SET_LOGO.equals(cmd)) {

			HttpSession session = request.getSession(true);
			String lang = (String) session.getAttribute(Messages.LANG);

			try {

				String webInfPath = this.getServletConfig().getServletContext()
						.getRealPath("WEB-INF");
				String rootWebPath = webInfPath.substring(0,
						webInfPath.indexOf("WEB-INF"));
				String uploadPath = rootWebPath + IMG_PATH;
				String tempPath = rootWebPath + PageConstants.UPLOAD_TEMP_PATH;

				if (!new File(uploadPath).isDirectory())
					new File(uploadPath).mkdirs();
				if (!new File(tempPath).isDirectory())
					new File(tempPath).mkdirs();
				DiskFileUpload fileUpload = new DiskFileUpload();

				fileUpload.setSizeMax(1 * 1024 * 1024);

				fileUpload.setSizeThreshold(4096);

				fileUpload.setRepositoryPath(tempPath);

				@SuppressWarnings("rawtypes")
				List items = fileUpload.parseRequest(request);
				@SuppressWarnings("rawtypes")
				Iterator itemIterator = items.iterator();

				while (itemIterator.hasNext()) {
					FileItem fi2 = (FileItem) itemIterator.next();

					if (!fi2.isFormField()) {
						int fileError = 0;
						String fileName = fi2.getName();
						if (fileName != null)
							fileName = fileName
									.substring(fileName
											.lastIndexOf(Symbols.DOUBLE_BACK_SLASH) + 1);
						if (fileName == null || fileName.equals(Symbols.BLANK))
							fileError = 1;
						String suffixName = null;
						if (fileError != 1) {
							suffixName = Symbols.DOT
									+ fileName.substring(fileName
											.lastIndexOf(Symbols.DOT) + 1);
							if (JPG_SUFFIX.equalsIgnoreCase(suffixName))
								if (lang != null
										&& lang.equals(Messages.LANG_EN)) {
									fileName = LOGO_EN;

								} else {
									fileName = LOGO_LOCAL;
								}

							File savedFile = new File(uploadPath, fileName); //

							fi2.write(savedFile);//

						}

					}
				}

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(Messages.MSG, msg);
			} catch (Exception e) {

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_UPLOAD_ERROR);
				} else {
					msg = Messages.getLabel(Messages.MSG_UPLOAD_ERROR);
				}
				request.setAttribute(Messages.MSG, msg);

				e.printStackTrace();
				return;
			}

		}
	}
	public void setBanner(HttpServletRequest request) throws IOException {
		String cmd = request.getParameter(PageConstants.CMD);
		if (SET_BANNER.equals(cmd)) {

			HttpSession session = request.getSession(true);
			String lang = (String) session.getAttribute(Messages.LANG);

			try {

				String webInfPath = this.getServletConfig().getServletContext()
						.getRealPath("WEB-INF");
				String rootWebPath = webInfPath.substring(0,
						webInfPath.indexOf("WEB-INF"));
				String uploadPath = rootWebPath + IMG_PATH;
				String tempPath = rootWebPath + PageConstants.UPLOAD_TEMP_PATH;

				if (!new File(uploadPath).isDirectory())
					new File(uploadPath).mkdirs();
				if (!new File(tempPath).isDirectory())
					new File(tempPath).mkdirs();
				DiskFileUpload fileUpload = new DiskFileUpload();

				fileUpload.setSizeMax(1 * 1024 * 1024);

				fileUpload.setSizeThreshold(4096);

				fileUpload.setRepositoryPath(tempPath);

				@SuppressWarnings("rawtypes")
				List items = fileUpload.parseRequest(request);
				@SuppressWarnings("rawtypes")
				Iterator itemIterator = items.iterator();

				while (itemIterator.hasNext()) {
					FileItem fi2 = (FileItem) itemIterator.next();

					if (!fi2.isFormField()) {
						int fileError = 0;
						String fileName = fi2.getName();
						if (fileName != null)
							fileName = fileName
									.substring(fileName
											.lastIndexOf(Symbols.DOUBLE_BACK_SLASH) + 1);
						if (fileName == null || fileName.equals(Symbols.BLANK))
							fileError = 1;
						String suffixName = null;
						if (fileError != 1) {
							suffixName = Symbols.DOT
									+ fileName.substring(fileName
											.lastIndexOf(Symbols.DOT) + 1);
							if (JPG_SUFFIX.equalsIgnoreCase(suffixName))
								 
									fileName = BANNER1_JPG;

								 

							File savedFile = new File(uploadPath, fileName); //

							fi2.write(savedFile);//

						}

					}
				}

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(Messages.MSG, msg);
			} catch (Exception e) {

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_UPLOAD_ERROR);
				} else {
					msg = Messages.getLabel(Messages.MSG_UPLOAD_ERROR);
				}
				request.setAttribute(Messages.MSG, msg);

				e.printStackTrace();
				return;
			}

		}
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.GROUP_ADMIN);
		return namespaces;
	}

}
